<template>
  <view class="chat-page">
    <!-- 顶部栏 -->
    <view class="chat-header">
      <image :src="targetUser.avatar" class="avatar" />
      <text class="nickname">{{ targetUser.nickname }}</text>
    </view>
    <!-- 消息列表 -->
    <scroll-view
      class="chat-body"
      scroll-y
      :scroll-into-view="scrollToView"
      :scroll-with-animation="true"
    >
      <view v-for="(msg, idx) in messages" :key="msg.id || msg._id || idx">
        <view :class="['msg-item', msg.isSelf ? 'self' : 'other', msg.isHistory && msg.isSelf ? 'history-self' : '']">
          <image :src="msg.avatar" class="msg-avatar" />
          <view class="msg-bubble">{{ msg.content }}</view>
        </view>
        <!-- 在历史消息和实时消息交界处插入分割线 -->
        <view v-if="idx === historyCount - 1 && historyCount > 0 && historyCount < messages.length" class="history-divider">
          <view class="history-line"></view>
          <text class="history-text">以上为历史消息</text>
          <view class="history-line"></view>
        </view>
      </view>
      <view :id="'bottom'"></view>
    </scroll-view>
    <!-- 输入区 -->
    <view class="chat-footer">
      <input
        ref="input"
        v-model="inputText"
        class="input"
        placeholder="请输入内容..."
        @confirm="sendMsg"
        confirm-type="send"
      />
      <button class="send-btn" @click="sendMsg">发送</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      targetUser: {
        avatar: '/static/default-avatar.png',
        nickname: '对方昵称'
      },
      messages: [],
      inputText: '',
      scrollToView: 'bottom',
      targetUserId: '',
      page: 1,
      pageSize: 20,
      loadingHistory: false,
      finished: false,
      historyCount: 0
    }
  },
  onLoad(options) {
    const targetUserId = options.targetUserId
    this.targetUserId = targetUserId
    // 获取对方用户信息
    const userObj = uniCloud.importObject('user')
    userObj.getUserInfo({ userId: targetUserId }).then(res => {
      if (res.code === 200) {
        this.targetUser = {
          avatar: res.data.avatar || '/static/default-avatar.png',
          nickname: res.data.nickname || '对方昵称'
        }
      }
    })
    // 拉取历史消息
    this.loadHistory()
  },
  methods: {
    async loadHistory() {
      if (this.loadingHistory || this.finished) return
      this.loadingHistory = true
      const userInfo = uni.getStorageSync('userInfo')
      const chatObj = uniCloud.importObject('chat',{customUI: true})
      const res = await chatObj.getChatHistory({
        userId: userInfo.userId,
        targetUserId: this.targetUserId,
        page: this.page,
        pageSize: this.pageSize
      })
      if (res.code === 200) {
        if (res.data.length < this.pageSize) this.finished = true
        // 处理头像和isSelf
        const msgs = res.data.map(msg => {
          if (msg.fromUserId === userInfo.userId) {
            // 自己发的
            return {
              ...msg,
              isSelf: true,
              avatar: userInfo.avatar || '/static/my-avatar.png',
              isHistory: true
            }
          } else {
            // 对方发的
            return {
              ...msg,
              isSelf: false,
              avatar: this.targetUser.avatar || '/static/default-avatar.png',
              isHistory: true
            }
          }
        })
        this.historyCount += msgs.length
        this.messages = [...this.messages, ...msgs]
        this.page++
        this.$nextTick(() => {
          this.scrollToView = ''
          this.$nextTick(() => {
            this.scrollToView = 'bottom'
            // 历史消息加载时不自动聚焦输入框
          })
        })
      }
      this.loadingHistory = false
    },
    async sendMsg() {
      if (!this.inputText.trim()) return;
      const userInfo = uni.getStorageSync('userInfo')
      const msg = {
        id: Date.now(),
        content: this.inputText,
        isSelf: true,
        avatar: userInfo.avatar || '/static/my-avatar.png',
        fromUserId: userInfo.userId,
        toUserId: this.targetUserId,
        createTime: Date.now()
      }
      this.messages.push(msg)
      this.inputText = ''
      this.$nextTick(() => {
        this.scrollToView = ''
        this.$nextTick(() => {
          this.scrollToView = 'bottom'
          // 发送消息后延迟聚焦输入框，避免与滚动冲突
          setTimeout(() => {
            this.$refs.input && this.$refs.input.focus && this.$refs.input.focus()
          }, 1000)
        })
      })
      // 新增：调用后端接口存储消息
      const chatObj = uniCloud.importObject('chat',{customUI: true})
      await chatObj.sendMessage({
        fromUserId: msg.fromUserId,
        toUserId: msg.toUserId,
        content: msg.content,
        avatar: msg.avatar,
        createTime: msg.createTime
      })
    }
  }
}
</script>

<style lang="scss">
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}
.chat-header {
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  .avatar {
    width: 64rpx;
    height: 64rpx;
    border-radius: 50%;
    margin-right: 20rpx;
  }
  .nickname {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
  }
}
.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
  background: #f5f5f5;
}
.msg-item {
  display: flex;
  align-items: flex-end;
  margin-bottom: 20rpx;
  &.self {
    flex-direction: row-reverse;
    .msg-bubble {
      background: #aee1ff;
      color: #222;
      border-top-right-radius: 0;
      border-top-left-radius: 20rpx;
    }
  }
  &.other {
    .msg-bubble {
      background: #fff;
      color: #222;
      border-top-left-radius: 0;
      border-top-right-radius: 20rpx;
    }
  }
  .msg-avatar {
    width: 56rpx;
    height: 56rpx;
    border-radius: 50%;
    margin: 0 16rpx;
  }
  .msg-bubble {
    max-width: 60vw;
    padding: 18rpx 28rpx;
    border-radius: 20rpx;
    font-size: 28rpx;
    word-break: break-all;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  }
}
.chat-footer {
  background: #fff;
  padding: 16rpx 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #eee;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  .input {
    flex: 1;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
    border: none;
    outline: none;
  }
  .send-btn {
    background: #1890ff;
    color: #fff;
    border-radius: 36rpx;
    font-size: 28rpx;
    padding: 0 32rpx;
    height: 72rpx;
    line-height: 72rpx;
    border: none;
  }
}
.history-divider {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20rpx 0 30rpx 0;
}
.history-line {
  flex: 1;
  height: 1px;
  background: #e0e0e0;
  margin: 0 16rpx;
}
.history-text {
  color: #999;
  font-size: 24rpx;
  padding: 0 10rpx;
}
.history-self {
  .msg-bubble {
    background: #fff !important;
    color: #222 !important;
    border-top-right-radius: 0 !important;
    border-top-left-radius: 20rpx !important;
    border: 1px solid #e0e0e0;
  }
}
</style> 